package com.example.sichuancuisine;

import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MenuFragment extends Fragment  {
    private View view;
    private int[] settingicon;
    private String[] foodnames;
    private String[] settingText;
    private ListView mListView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //加载布局文件
        view=inflater.inflate(R.layout.fragment_menu,container,false);
        //获取MainActivity对象实例
        MainActivity activity=(MainActivity)getActivity();
        settingicon=activity.getIcons();
        foodnames=activity.getNames();
        settingText=activity.getSettingText();
        if(view!=null){
            initview();
        }
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                ContentFragment listFragment=
//                        (ContentFragment) ((MainActivity)getActivity()).getSupportFragmentManager().findFragmentById(R.id.foodcontent);
//                listFragment.setText(settingText[i]);
                ContentFragment contentFragment=
                        (ContentFragment) ((MainActivity)getActivity()).getSupportFragmentManager().findFragmentById(R.id.foodcontent);
                contentFragment.setText(settingText[i]);
            }
        });
        return view;
    }

    private void initview() {
        mListView=(ListView) view.findViewById(R.id.menulist);
        if(settingicon!=null){
            mListView.setAdapter(new MyAdapter());
        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return settingicon.length;
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return settingicon[i];
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view=View.inflate(getActivity(),R.layout.item_list,null);
            ImageView imageView=(ImageView) view.findViewById(R.id.food_icon);
            imageView.setBackgroundResource(settingicon[i]);
            TextView textView=(TextView) view.findViewById(R.id.food_name);
            textView.setText(foodnames[i]);
            return view;
        }
    }
}
